package LC;

import java.util.Stack;

/**
 * @ClassName LC32
 * @Description: TODO
 * @Author hl
 * @Date 2021/4/16
 * @Version V1.0
 **/
public class LC32 {
    public static int longestValidParentheses(String s) {
    int res=0;
    Stack<Integer> stack=new Stack<>();
    stack.push(-1);
    for(int i=0;i<s.length();i++){
        if(s.charAt(i)=='('){
            stack.push(i);
        }else{
            stack.pop();
            if(stack.isEmpty()){//表示当前的右括号不可以被匹配，要存入当前有括号的下标
                stack.push(i);
            }else{//当前右括号可以被匹配，那就比较并更新res
                res=Math.max(res,i-stack.peek());
            }
        }
    }
    return res;
    }

    public static void main(String[] args) {
        String s = ")()())";
        System.out.println(longestValidParentheses(s));
    }

}
